<template>
  <a-card :bordered="false">

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="12">

          <!-- <a-col :md="4" :sm="8">
            <a-form-item label="车场">
              <a-select placeholder="请选择车场" v-model="queryParam.parkCode" :options="parkInfos"
                        @select="parkInfoSelect"></a-select>

            </a-form-item>
          </a-col> -->
          <a-col :md="4" :sm="8">
            <a-form-item label="权限组名称">
              <a-select placeholder="请选择权限组" v-model="queryParam.id" :options="permissionGroups"
              ></a-select>
            </a-form-item>
          </a-col>
          <a-col :md="4" :sm="8">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button style="margin-right: 10px" @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button v-show="showSaveBtn" @click="handleSave" type="primary">保存更改</a-button>
    </div>
    <div>
      <a-row>
        <!-- 树-->
        <a-col :md="4" :sm="4">
          <a-divider orientation="left" style="margin-top: 2px;">
            权限组
          </a-divider>
          <template>
            <a-dropdown :trigger="[this.dropTrigger]" @visibleChange="dropStatus">
                <span style="user-select: none">
                  <a-tree
                    :selectedKeys="selectedKeys"
                    :checkedKeys="checkedKeys"
                    :checkStrictly="true"
                    checkable
                    @select="onSelect"
                    @check="onCheck"
                    @rightClick="rightHandle"
                    @expand="onExpand"
                    v-if="treeData.length"
                    :tree-data="treeData"
                    :default-expanded-keys="this.keyId"
                  />
                </span>
              <!--新增右键点击事件,和增加添加和删除功能-->
              <a-menu slot="overlay">
                <a-menu-item @click="handleEdit()" key="6">重命名</a-menu-item>
                <a-menu-item>
                  <a-popconfirm title="确定删除吗?" @confirm="() => deletePermissionGroupById()">
                    <a>删除</a>
                  </a-popconfirm>
                </a-menu-item>
                <a-menu-item @click="closeDrop" key="3">取消</a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>
        </a-col>
        <a-col :md="1" :sm="1">
        </a-col>
        <a-col :md="19" :sm="19">
          <div style="font-size: 16px;color:rgba(0, 0, 0, 0.85)">授权区域</div>
          <a-table
            ref="table"
            size="middle"
            bordered
            rowKey="id"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange">
          </a-table>
        </a-col>
      </a-row>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <permissionGroup-modal ref="modalForm" @ok="modalFormOk"></permissionGroup-modal>

  </a-card>
</template>

<script>
import PermissionGroupModal from './modules/PermissionGroupModal'
import {JeecgListMixin} from '@/mixins/JeecgListMixin'
import {deleteAction, postAction, getAction, downFile} from '@/api/manage'
import { getMonthlyParkInfoList } from '@api/api'
import {filterObj} from '@/utils/util';

export default {
  name: "PermissionGroupList",
  mixins: [JeecgListMixin],
  components: {
    PermissionGroupModal,
  },
  data() {
    return {
      description: '权限组表管理页面',
      // 表头
      columns: [
        {
          title: '停车场编号',
          align: "center",
          dataIndex: 'parkCode'
        },
        {
          title: '区域名称',
          align: "center",
          dataIndex: 'areaName'
        },
        {
          title: '区域类型',
          align: "center",
          dataIndex: 'areaType',
          customRender: function (t, r, index) {
            if (t === 0) {
              return "小区域"
            }
            if (t === 1) {
              return "大区域"
            }
          }
        },

      ],
      url: {
        list: "/permissionGroup/list",
        getParkInfos: "/parking/parkInfo/parkInfoList",
        getParkPermissionGroup: "/permissionGroup/getParkPermissionGroup",
        getPermissionGroup: "/permissionGroup/getPermissionGroup",
        getAreasByParkCode: "/permissionArea/getAreasByParkCode",
        deletePermissionAreaByAreaId: "/permissionArea/updatePermissionAreaByAreaIds",
        delete: "/permissionGroup/delete",
        deleteBatch: "/permissionGroup/deleteBatch",
        exportXlsUrl: "/permissionGroup/exportXls",
        importExcelUrl: "/permissionGroup/importExcel",
      },
      queryParam: {
        "opTime_begin": "",
        "opTime_end": "",
        "type": "-1",
        "parkCode": "",
        "id": "",
        "permissionGroupId": ""

      },
      isorter: {
        column: 'createTime',
        order: 'desc',
      },
      parkInfos: [],
      permissionGroups: [{label: '请选择权限组', value: ''}],

      dropTrigger: '',
      checkedKeys: [],
      selectedKeys: [],
      keyId: [],
      treeData: [],
      orgType: 0,
      selectedRowKeys: [],
      ids: [],
      unBindAreaIds: [],
      sourceBindAreaIds: [],
      // sourceUnBindAreaIds: []
      showSaveBtn:false
    }
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    }
  },
  created() {

    this.loadParkInfo()
  },
  methods: {
    parkInfoSelect() {
      //每次车场改变时都查对应的权限组列表
      //先清空被选的权限组
      this.queryParam.id = ""
      // this.loadPermissionGroup()
      //每次车场变化时查该车场的所有区域
      this.loadPermissionGroup()
    },
    modalFormOk() {
      this.loadParkPermissionGroup()
    },
    loadParkPermissionGroup() {
      const that = this
      getAction(this.url.getParkPermissionGroup, {
        parkCode: this.queryParam.parkCode,
        id: this.queryParam.id
      }).then((res) => {
        if (res.success) {
          that.treeData = res.result;
          that.loadData(1)
          that.loading = false
        }
      })
    },
    onSelectChange(e) {
      //保存权限组和区域的绑定状态，点击保存更改时才改变状态
      this.selectedRowKeys = e
      this.showSaveBtn=true
    },
    handleEdit() {
      var records = this.treeData.filter(item => {
        return item.key === this.selectedKeys[0]
      })
      var record = records[0]
      this.$refs.modalForm.title = "重命名";
      this.$refs.modalForm.edit(record);
    },
    handleAdd() {
      var record = {}
      record.parkCode = this.queryParam.parkCode
      this.$refs.modalForm.edit(record);
    },

    dealAreaIds() {
      //求补集
      var that = this
      //unBindAreaIds表示与权限组取消绑定关系的区域id集合
      that.unBindAreaIds=[]
        this.ids.filter(function (id) {
          if (!that.selectedRowKeys.includes(id)) {
            that.unBindAreaIds.push(id)
          }
        })
      that.areaIds=[]
        this.ids.filter(function (id) {
          if (that.selectedRowKeys.includes(id)) {
            that.areaIds.push(id)
          }
        })
    },
    handleSave(){
      this.dealAreaIds();
      this.updateAreaIdsRelation();
      this.showSaveBtn=false
    },

    updateAreaIdsRelation(){
      const that = this
      postAction(that.url.deletePermissionAreaByAreaId, {
        "unBindAreaIds": that.unBindAreaIds,
        "areaIds": that.areaIds,
        "permissionGroupId": that.queryParam.permissionGroupId
      }).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadData(1);
        }
      })
    },

    onCheck(checkedKeys, info) {
      this.hiding = false
      this.onSelect(checkedKeys, info)
    },
    // 右键操作方法
    rightHandle(node) {
      window.localStorage.setItem('deptId', node.node.dataRef.id);
      this.dropTrigger = 'contextmenu';
      this.orgType = node.node.dataRef.orgType;
      this.departName = node.node.dataRef.departName;
      this.rightClickSelectedKey = node.node.eventKey;

      this.selectedKeys = [node.node.dataRef.key];
      this.checkedKeys = [node.node.dataRef.key];
    },

    onExpand(expandedKeys) {
      this.iExpandedKeys = expandedKeys
    },

    // 右键点击下拉框改变事件
    dropStatus(visible) {
      if (visible == false) {
        this.dropTrigger = ''
      }
    },
    // 右键店家下拉关闭下拉框
    closeDrop() {
      this.dropTrigger = ''
    },

    //判断是否有修改改变
    haveOperation(){
      //unBindAreaIds表示所有未与权限组绑定的区域id集合，包含曾经是绑定状态然后用户取消了
      var that = this
      this.unBindAreaIds = []
      this.ids.filter(function (id) {
        if (!that.selectedRowKeys.includes(id)) {
          that.unBindAreaIds.push(id)
        }
      })
      //areaIds表示所有与权限组绑定的区域id集合，包含曾经不是绑定状态然后用户添加了绑定关系
      this.areaIds = []
      this.ids.filter(function (id) {
        if (that.selectedRowKeys.includes(id)) {
          that.areaIds.push(id)
        }
      })
      //判断两个数组所有元素是否相等
      // let  b1 = that.areaIds.length === that.sourceBindAreaIds.length && that.areaIds.every(a => that.sourceBindAreaIds.some(b => a === b)) && that.sourceBindAreaIds.every(_b => that.areaIds.some(_a => _a === _b));
      // let  b2 = that.unBindAreaIds.length === that.sourceUnBindAreaIds.length && that.unBindAreaIds.every(a => that.sourceUnBindAreaIds.some(b => a === b)) && that.sourceUnBindAreaIds.every(_b => that.unBindAreaIds.some(_a => _a === _b));
      let b1 = that.areaIds.sort().toString() == that.sourceBindAreaIds.sort().toString()
      //如果初始该权限组绑定的区域id集合与当前绑定的区域id集合不一致，说明用户进行了修改
      //如果初始该权限组未绑定的区域id集合与当前未绑定的区域id集合不一致，说明用户进行了修改
      if (!b1) {
        that = this
        this.$confirm({
          title: '提示',
          content: ' 您当前的操作还未保存，是否保存？',
          onOk() {
            that.updateAreaIdsRelation();
            that.hiding = false
            // let record = e.node.dataRef
            // that.selectedKeys = [record.key];
            // that.checkedKeys = [record.key];
            //查询该权限组下的所有区域信息
            that.queryParam.permissionGroupId = that.selectedKeys[0]
            that.loadData(1)
          },
          onCancel() {
            that.hiding = false
            // let record = e.node.dataRef
            // that.selectedKeys = [record.key];
            // that.checkedKeys = [record.key];
            //查询该权限组下的所有区域信息
            that.queryParam.permissionGroupId = that.selectedKeys[0]
            that.loadData(1)
          },
        })
      }else{
        that.hiding = false
        // let record = e.node.dataRef
        // that.selectedKeys = [record.key];
        // that.checkedKeys = [record.key];
        //查询该权限组下的所有区域信息
        that.queryParam.permissionGroupId = that.selectedKeys[0]
        that.loadData(1)
      }
    },

    onSelect(selectedKeys, e) {
      let record = e.node.dataRef
      this.selectedKeys = [record.key];
      this.checkedKeys = [record.key];
      this.haveOperation()
    },
    loadPermissionGroup() {
      //根据当前的车场加载权限组
      const that = this
      getAction(this.url.getPermissionGroup, {parkCode: this.queryParam.parkCode}).then((res) => {
        if (res.success) {
          that.permissionGroups = [{label: '请选择权限组', value: ''}],
            res.result.forEach(permissionGroup => {
              that.permissionGroups.push({
                label: permissionGroup.permissionName,
                value: permissionGroup.id
              })
            })
          that.loading = false
        }
      })
    },
    loadParkInfo() {
      const that = this
      getMonthlyParkInfoList().then((res) => {
        if (res.success) {
          if (res.result) {
            that.parkInfos = []
            res.result.forEach(parkInfo => {
              that.parkInfos.push({
                label: parkInfo.parkName,
                value: parkInfo.parkCode
              })
            })
            that.queryParam.parkCode = that.parkInfos[0].value
            that.loadPermissionGroup()
            that.loadParkPermissionGroup()
            that.loadData()
          }
        }
      })
    },
    handleExportXls(fileName) {

      let startTime = this.queryParam.opTime_begin;
      let endTime = this.queryParam.opTime_end;
      let opDesc = this.queryParam.opDesc;
      let dayTime = startTime;
      if (startTime == "") {
        this.$message.error("请选择导出开始日期");
        return
      }
      if (endTime == "") {
        this.$message.error("请选择导出结束日期");
        return
      }
      if (startTime != "" && endTime != "") {
        if (startTime != endTime) {
          this.$message.error("仅支持1天数据导出,请选择导出日期");
          return
        }
      }

      if (startTime == "" && endTime != "") {
        this.$message.error("请选择开始时间");
        return
      }

      if (startTime != "" && endTime == "") {
        this.$message.error("请选择结束时间");
        return
      }


      this.queryParam.dayTime = dayTime;
      fileName = dayTime + fileName;
      let param = {...this.queryParam};
      if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
        param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
        param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
      }

      downFile(this.url.exportXlsUrl, param).then((data) => {
        if (!data) {
          this.$message.warning("文件下载失败")
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data]), fileName + '.xls')
        } else {
          let url = window.URL.createObjectURL(new Blob([data]))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xls')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(url); //释放掉blob对象
        }
      })
    },


    onChangeStartTime(date, dateString) {
      this.queryParam.opTime_begin = dateString;
    },

    onChangeEndTime(date, dateString) {
      this.queryParam.opTime_end = dateString;
    },


    loadData(arg) {
      if (!this.url.getAreasByParkCode) {
        this.$message.error("请设置url.getAreasByParkCode属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      var that = this
      getAction(this.url.getAreasByParkCode, params).then((res) => {
        if (res.success) {
          that.dataSource = res.result.page.records;
          //初始绑定的区域id集合
          that.sourceBindAreaIds = res.result.bindAreaIdList;
          that.ids = that.dataSource.map(element => element.id);
          //所有绑定的区域id列表
          that.selectedRowKeys = res.result.bindAreaIdList;
          that.ipagination.total = res.result.page.total;
        }
        if (res.code === 510) {
          that.$message.warning(res.message)
        }
        that.loading = false;
      })
    },

    searchQuery() {
      // this.haveOperation('search')
      this.dataSource = []
      this.loadParkPermissionGroup();
      this.selectedKeys = []
      this.checkedKeys = []
      this.selectedRowKeys = []
      this.queryParam.permissionGroupId = ''
      this.loadData()
    },

    getQueryParams() {

      var param = Object.assign({}, this.isorter, this.queryParam);
      param.field = this.getQueryField();
      param.pageNo = this.ipagination.current;
      param.pageSize = this.ipagination.pageSize;
      if (this.queryParam.opTime_begin != "" && this.queryParam.opTime_end != "") {
        param.opTime_begin = this.queryParam.opTime_begin + " 00:00:00";
        param.opTime_end = this.queryParam.opTime_end + " 23:59:59";
      }

      // delete param.createTimeRange; // 时间参数不传递后台
      return filterObj(param);
    },

    deletePermissionGroupById() {
      if (!this.url.delete) {
        this.$message.error("请设置url.delete属性!")
        return
      }
      var that = this;
      deleteAction(that.url.delete, {id: this.selectedKeys[0]}).then((res) => {
        if (res.success) {
          that.$message.success(res.message);
          that.loadParkPermissionGroup();
        } else {
          that.$message.warning(res.message);
        }
      });
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less'
</style>